package com.wk.cart.listener;

import com.wk.common.constant.RedisKey;
import com.wk.common.constant.mq.ItemExchange;
import com.wk.common.constant.mq.ItemQueue;
import com.wk.common.constant.mq.ItemRoutingKey;
import com.wk.pms.entity.SkuInfo;
import com.wk.pms.feign.SkuInfoFeign;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class CartListener {

    @Autowired
    private SkuInfoFeign skuInfoFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 订单创建成功后删除购物车中已下单的商品
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = ItemExchange.ORDER_EXCHANGE, ignoreDeclarationExceptions = "true"),
            value = @Queue(value = ItemQueue.CART_DELETE_QUEUE,durable = "true"),
            key = ItemRoutingKey.CART_DELETE
    ))
    public void cartDeleteListener(Map<String,Object> cartMap) {
        String userId = cartMap.get("userId").toString();
        List<Object> skuIds = (List<Object>) cartMap.get("skuIds");
        skuIds.forEach(skuId->redisTemplate.boundHashOps(RedisKey.CART_ITEM + userId).delete(skuId.toString()));
    }


    /**
     * 监听spu的修改，并获取spu下所有sku的价格，更新购物车中对应的商品价格
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = ItemExchange.PMS_EXCHANGE, ignoreDeclarationExceptions = "true"),
            value = @Queue(value = ItemQueue.CART_PRICE_QUEUE, durable = "true"),
            key = {ItemRoutingKey.ITEM_UPDATE}
    ))
    public void cartPriceListener(Long spuId) {

        List<SkuInfo> skus = skuInfoFeign.queryBySpuId(spuId).getData();

        //遍历sku集合 更新Redis中对应sku的价格
        skus.forEach(sku -> {
            redisTemplate.boundValueOps(RedisKey.CART_PRICE + sku.getSkuId().toString()).set(sku.getPrice().toString());
        });
    }
}
